<?php
class Sample {
    const API_KEY = "";
    const SECRET_KEY = "";

    public function run() {
        if(isset($_POST['text']) && isset($_POST['url'])){
            $text = $_POST['text'];
            $url = $_POST['url'];
            $curl = curl_init();
            curl_setopt_array($curl, array(
                CURLOPT_URL => "https://aip.baidubce.com/rpc/2.0/ernievilg/v1/txt2imgv2?access_token={$this->getAccessToken()}",
                CURLOPT_TIMEOUT => 30,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_SSL_VERIFYPEER  => false,
                CURLOPT_SSL_VERIFYHOST  => false,
                CURLOPT_CUSTOMREQUEST => 'POST',
                // image 可以通过 $this.getFileBase64Content("C:\fakepath\149.png") 方法获取
                CURLOPT_POSTFIELDS =>'{"prompt":"'.$text.'","width":1024,"height":1024,"image_num":1,"url":"'.$url.'","change_degree":1}',
        
                CURLOPT_HTTPHEADER => array(
                    'Content-Type: application/json',
                    'Accept: application/json'
                ),

            ));
            $response = curl_exec($curl);
            curl_close($curl);
            return $response;
        }
    }
    
    /**
     * 获取文件base64编码
     * @param string  $path 文件路径
     * @return string base64编码信息，不带文件头
     */
    private function getFileContentAsBase64($path){
        
        return urlencode(base64_encode(file_get_contents($path)));
        
    }
    
    /**
     * 使用 AK，SK 生成鉴权签名（Access Token）
     * @return string 鉴权签名信息（Access Token）
     */
    private function getAccessToken(){
        $curl = curl_init();
        $postData = array(
            'grant_type' => 'client_credentials',
            'client_id' => self::API_KEY,
            'client_secret' => self::SECRET_KEY
        );
        curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://aip.baidubce.com/oauth/2.0/token',
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_SSL_VERIFYPEER  => false,
            CURLOPT_SSL_VERIFYHOST  => false,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POSTFIELDS => http_build_query($postData)
        ));
        $response = curl_exec($curl);
        curl_close($curl);
        $rtn = json_decode($response);
        return $rtn->access_token;
    }
}

$rtn = (new Sample())->run();
if(isset($_POST['text']) && isset($_POST['url'])){
    $rel = json_decode($rtn)->data->task_id;
    echo '<script>window.location.href = "img2img2.php?id='.$rel.'";</script>';
}
?>
<html>
    <head>
        <title>图星（图生图）</title>
        <meta charset="utf-8">
    </head>
    <body>
        <form method="POST" action="img2img.php">
            <center><h1>图星（图生图）</h1></center>
            <center>输入提示词<input type="text" name ="text" value="">
            输入参考图<input type="text" name="url" value="">
            <input type="submit" value="提交">
            </center>
        </form>
    </body>
</html>